package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.cart.utils.UserHolder;
import com.leyou.common.auth.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    private static final String KEY_PREFIX = "cart:add:uid:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void addCart(Cart cart) {
        // 1.获取登录用户
        UserInfo userInfo = UserHolder.getUser();

        // 2.购物车的key，主要是用户的id
        String key = KEY_PREFIX +  userInfo.getId();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        // 3.判断当前用户购物车中，是否已经存在要加入的商品
        String skuId = cart.getSkuId().toString();
        Boolean isExists = hashOps.hasKey(skuId);
        if(BooleanUtils.isTrue(isExists)) {
            Integer num = cart.getNum();
            // 4.存在了，在原有数量上 加 cart参数的数量
            String json = hashOps.get(skuId);
            cart = JsonUtils.toBean(json, Cart.class);
            cart.setNum(num + cart.getNum());
        }
        // 写回redis
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        // 1.获取登录用户
        UserInfo userInfo = UserHolder.getUser();

        // 2.购物车的key，主要是用户的id
        String key = KEY_PREFIX +  userInfo.getId();
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        // 3.获取所有购物车数据
        List<String> list = hashOps.values();
        if(CollectionUtils.isEmpty(list)){
            // 购物车为空
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 4.处理json
        return list.stream()
                .map(json -> JsonUtils.toBean(json, Cart.class))
                .collect(Collectors.toList());
    }
}
